const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const userId = wxContext.OPENID;
  
  if (!userId) {
    return {
      code: 1,
      message: '用户未登录'
    };
  }
  
  try {
    const { timeSlotKey } = event;
    
    // 参数验证
    if (!timeSlotKey) {
      return {
        code: 2,
        message: '参数不完整'
      };
    }
    
    // 1. 先检查是否已有学习记录（匹配成功）
    const studyRecord = await db.collection('study_records')
      .where({
        userId,
        status: 'not_started' // 只查询未开始的学习记录
      })
      .orderBy('createTime', 'desc')
      .limit(1)
      .get();
    
    console.log('查询学习记录结果:', studyRecord.data);
    
    if (studyRecord.data.length > 0) {
      const record = studyRecord.data[0];
      console.log('找到学习记录:', record);
      
      // 验证时间段是否匹配（通过生成timeSlotKey比较）
      const recordTimeSlotKey = generateTimeSlotKey(record.startTime, record.endTime);
      console.log('记录的timeSlotKey:', recordTimeSlotKey, '请求的timeSlotKey:', timeSlotKey);
      
      if (recordTimeSlotKey === timeSlotKey) {
        
        console.log('返回匹配成功数据:', {
          studyRecordId: record._id,
          matchId: record.matchId,
          startTime: record.startTime,
          endTime: record.endTime,
          duration: record.duration
        });
        
        return {
          code: 0,
          message: '匹配成功',
          data: {
            status: 'matched',
            studyRecordId: record._id,
            matchId: record.matchId,
            timeSlotKey,
            startTime: record.startTime,
            endTime: record.endTime,
            duration: record.duration.toString() // 确保duration是字符串格式
          }
        };
      } else {
        // 宽松回退：从请求的 timeSlotKey 中解析 HH:mm-HH:mm 比较
        try {
          const keyStr = String(timeSlotKey || '');
          const rangePart = keyStr.includes('_') ? keyStr.split('_').slice(1).join('_') : keyStr;
          let parsedStart = null;
          let parsedEnd = null;
          if (rangePart.includes('-')) {
            const parts = rangePart.split('-');
            const left = parts[0];
            const right = parts[1];
            parsedStart = left.includes('_') ? left.split('_').pop() : left;
            parsedEnd = right.includes('_') ? right.split('_').pop() : right;
          }
          if (parsedStart && parsedEnd && parsedStart === record.startTime && parsedEnd === record.endTime) {
            // 视为匹配成功
            console.log('宽松匹配命中，返回匹配成功数据');
            return {
              code: 0,
              message: '匹配成功',
              data: {
                status: 'matched',
                studyRecordId: record._id,
                matchId: record.matchId,
                timeSlotKey,
                startTime: record.startTime,
                endTime: record.endTime,
                duration: record.duration.toString()
              }
            };
          } else {
            console.log('时间槽不匹配，继续查找匹配池');
          }
        } catch (e) {
          console.log('宽松回退解析失败，继续查找匹配池', e);
        }
      }
    } else {
      console.log('没有找到学习记录，查找匹配池');
    }
    
    // 2. 检查是否还在匹配池中
    const poolRecord = await db.collection('matching_pool')
      .where({ userId, timeSlotKey })
      .get();
    
    if (poolRecord.data.length > 0) {
      return {
        code: 0,
        message: '等待匹配中',
        data: {
          status: 'waiting',
          timeSlotKey
        }
      };
    }
    
    // 3. 既不在学习记录中，也不在匹配池中
    return {
      code: 1,
      message: '未找到匹配信息',
      data: {
        status: 'not_found'
      }
    };
  } catch (error) {
    console.error('检查匹配状态出错:', error);
    return { 
      code: 500, 
      message: '服务器错误',
      error: error.message 
    };
  }
};

// 生成时间槽键值（与joinMatchingPool保持一致）
function generateTimeSlotKey(startTime, endTime) {
  const now = new Date();
  const currentHour = now.getHours();
  const currentMinute = now.getMinutes();
  const currentTotalMinutes = currentHour * 60 + currentMinute;
  
  const [startHour, startMinute] = startTime.split(':').map(Number);
  const [endHour, endMinute] = endTime.split(':').map(Number);
  const startTotalMinutes = startHour * 60 + startMinute;
  const endTotalMinutes = endHour * 60 + endMinute;
  
  // 确定开始日期
  let startDate;
  if (startTotalMinutes <= currentTotalMinutes) {
    // 开始时间 <= 当前时间 → 次日
    startDate = new Date(now.getTime() + 24 * 60 * 60 * 1000);
  } else {
    // 开始时间 > 当前时间 → 当天
    startDate = now;
  }
  
  // 确定结束日期
  let endDate;
  if (endTotalMinutes <= startTotalMinutes) {
    // 结束时间 <= 开始时间，说明跨天到下一天
    endDate = new Date(startDate.getTime() + 24 * 60 * 60 * 1000);
  } else {
    // 结束时间 > 开始时间，同一天
    endDate = startDate;
  }
  
  const startDateStr = startDate.toISOString().split('T')[0];
  const endDateStr = endDate.toISOString().split('T')[0];
  
  // 生成包含完整日期信息的键值
  if (startDateStr === endDateStr) {
    // 同一天
    return `${startDateStr}_${startTime}-${endTime}`;
  } else {
    // 跨天
    return `${startDateStr}_${startTime}-${endDateStr}_${endTime}`;
  }
}
